<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			img[lazyload] {
				width: 900px;
				height: 700px;
			}
		</style>
	</head>

	<body>
		<img lazyload src="img/loading.png" data-src="http://shfthk.com/img/banner/33.png" />
		<img lazyload src="img/loading.png" data-src="http://shfthk.com/img/youshi/6.png" />
		<img lazyload src="img/loading.png" data-src="https://imgsa.baidu.com/news/q%3D100/sign=35e6955663224f4a5199771339f79044/64380cd7912397dd26597b745782b2b7d0a2879a.jpg" />
		<img lazyload src="img/loading.png" data-src="http://shfthk.com/img/youshi/5.png" />

		<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
		<script type="text/javascript">
			//			const loadImgAsync = function(src, success) {
			//				var img = new Image()
			//				img.src = src
			//				img.onload = () => {
			//					console.log("请求成功")
			//					success()
			//				}
			//
			//				img.onerror = () => {
			//					console.log("请求失败")
			//				}
			//			}
			//
			//			$("img[lazyload]").each(function() {
			//				var _this = this
			//				loadImgAsync($(this).data("src"), function() {
			//					$(_this).prop("src", $(_this).data("src"))
			//				})
			//			})

			const loadImgAsync = function(src) {
				return new Promise(function(resolve, reject) {
					console.log("开始请求" + src)
					var img = new Image()
					img.src = src
					img.onload = () => {
						console.log("请求成功")
						resolve(src)
					}

					img.onerror = () => {
						console.log("请求失败")
						reject(src)
					}
				})
			}

			//			$("img[lazyload]").first().each(function() {
			//				loadImgAsync($(this).data("src")).then(res => {
			//					$(this).prop("src", res)
			//				}).catch(res => {
			//					console.log(res + "请求失败")
			//				})
			//			})

			var loadimg = () => {
				$("img[lazyload]").each(function() {
					if($(this).position().top - $(window).scrollTop() < $(window).innerHeight() + 500) {
						if($(this).attr("src") === "img/loading.png") {
							loadImgAsync($(this).data("src")).then(res => {
								$(this).prop("src", res)
							}).catch(res => {
								console.log(res + "请求失败")
							})
						}
					}
				})
			}
			loadimg()
			$(window).scroll(function() {
				loadimg()
			})
		</script>

	</body>

</html>